<?php

$host = '127.0.0.1';
$user = 'dancelin_agent';
$pwd = 'brachmasamhita';
$db = 'dancelin_warehouse';

$action = $_REQUEST["action"];

if($action == "remove") {
   doRemove();	
} else if($action == "save") {
   doSave();	
} else if($action == "list") {
   doList();	
}  else if($action == "count") {
   doCount();	
} 


function doList() {
   $db_handle = mysql_connect($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pwd']);
   mysql_select_db($GLOBALS['db'], $db_handle);

   @mysql_query("SET NAMES cp1251");
   
   $wSql = "active=1";
   if($_REQUEST["id"] != null) $wSql = $wSql.' and id='.$_REQUEST["id"];
   if($_REQUEST["type"] != null) $wSql = $wSql.' and type='.$_REQUEST["type"];
   if($_REQUEST["category"] != null) $wSql = $wSql.' and category='.$_REQUEST["category"];
   if($_REQUEST["latitude"] != null && $_REQUEST["longitude"] != null) $wSql = $wSql.' and 3963.191 * ACOS((SIN(PI() * '.$_REQUEST["latitude"].'/180000000) * SIN(PI() * latitude/180000000)) + (COS(PI() * '.$_REQUEST["latitude"].'/180000000) * cos(PI() * latitude/180000000) * COS(PI() * longitude/180000000 - PI() * '.$_REQUEST["longitude"].'/180000000)) ) <= 10';
   $q = mysql_query("select * from dancelin_warehouse.tickets where ".$wSql." order by date desc", $db_handle) or die(mysql_error());
   while($e = mysql_fetch_assoc($q)) {
      while(list($key, $val) = each($e)) {
         $val = iconv("windows-1251", "UTF-8", $val);
	 $out[$key] = $val;
      }
      $output[] = $out;
   }
   print_r(json_encode($output));
    
   mysql_close();
}

function doCount() {
   $db_handle = mysql_connect($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pwd']);
   mysql_select_db($GLOBALS['db'], $db_handle);

   $q = mysql_query("select count(1) as lost from dancelin_warehouse.tickets where type=0 and active=1", $db_handle) or die(mysql_error());
   while($e=mysql_fetch_assoc($q))
      $output[]=$e;
   $q = mysql_query("select count(1) as found from dancelin_warehouse.tickets where type=1 and active=1", $db_handle) or die(mysql_error());
   while($e=mysql_fetch_assoc($q))
      $output[]=$e;
   print_r(json_encode($output));
   
   mysql_close();
}


function doSave() {
   $db_handle = mysql_connect($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pwd']);
   mysql_select_db($GLOBALS['db'], $db_handle);
   
   @mysql_query("SET NAMES cp1251");
   
   $name=iconv("UTF-8", "windows-1251", $_REQUEST['name']);
   $description=iconv("UTF-8", "windows-1251", $_REQUEST['description']);
   
   $date=$_REQUEST['date'];
   $type=$_REQUEST['type'];
   $category=$_REQUEST['category'];
   //$name=$_REQUEST['name'];
   //$description=$_REQUEST['description'];
   $latitude=$_REQUEST['latitude'];
   $longitude=$_REQUEST['longitude'];
   $phone=$_REQUEST['contactPhone'];
   mysql_query("insert into dancelin_warehouse.tickets(date, type, category, name, description, latitude, longitude, contact_phone) values('".$date."',".$type.",".$category.",'".$name."','".$description."',".$latitude.",".$longitude.",'".$phone."')");
   $q=mysql_query("select LAST_INSERT_ID()");
   while($e=mysql_fetch_assoc($q)) {
      $output[]=$e; 
   }
   print(json_encode($output));
   
   mysql_close();


}


function doRemove() {
   $db_handle = mysql_connect($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pwd']);
   mysql_select_db($GLOBALS['db'], $db_handle);

   mysql_query("update dancelin_warehouse.tickets set active=0 where id=".$_REQUEST['id']) or die(mysql_error());
 
   mysql_close();
}

function _json_encode($value) 
    {
        if (is_int($value)) {
            return (string)$value;   
        } elseif (is_string($value)) {
	        $value = str_replace(array('\\', '/', '"', "\r", "\n", "\b", "\f", "\t"), 
	                             array('\\\\', '\/', '\"', '\r', '\n', '\b', '\f', '\t'), $value);
	        $convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
	        $result = "";
	        for ($i = mb_strlen($value) - 1; $i >= 0; $i--) {
	            $mb_char = mb_substr($value, $i, 1);
	            if (mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match)) {
	                $result = sprintf("\\u%04x", $match[1]) . $result;
	            } else {
	                $result = $mb_char . $result;
	            }
	        }
	        return '"' . $result . '"';                
        } elseif (is_float($value)) {
            return str_replace(",", ".", $value);         
        } elseif (is_null($value)) {
            return 'null';
        } elseif (is_bool($value)) {
            return $value ? 'true' : 'false';
        } elseif (is_array($value)) {
            $with_keys = false;
            $n = count($value);
            for ($i = 0, reset($value); $i < $n; $i++, next($value)) {
                        if (key($value) !== $i) {
			      $with_keys = true;
			      break;
                        }
            }
        } elseif (is_object($value)) {
            $with_keys = true;
        } else {
            return '';
        }
        $result = array();
        if ($with_keys) {
            foreach ($value as $key => $v) {
                $result[] = _json_encode((string)$key) . ':' . _json_encode($v);    
            }
            return '{' . implode(',', $result) . '}';                
        } else {
            foreach ($value as $key => $v) {
                $result[] = _json_encode($v);    
            }
            return '[' . implode(',', $result) . ']';
        }
    } 

?>